package xdu.lz.stage7_jucCollection.blockingqueue;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;

/**
 * Created at 2019/10/28 0028 下午 10:49
 * --
 */
public class SynQueue {

    /**
     * 直接add会报错，因为没有容量。需要有人take，此时才能add，会立马被拿出来。
     * @throws InterruptedException
     */
    @Test
    public void testTake() throws InterruptedException {
        SynchronousQueue<Integer> queue = new SynchronousQueue<>();
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(()-> {
            try {
                System.out.println("take元素被阻塞住...");
//                Retrieves and removes the head of this queue, waiting if necessary
//                for another thread to insert it.
                Integer take = queue.take();
                System.out.println("有元素被插入了..."+take);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread.sleep(1000);
        System.out.println("元素1被插入了，可以被拿了..");
        queue.add(1);
//             * Adds the specified element to this queue, waiting if necessary for
//     * another thread to receive it.
    }

    @Test
    public void testPut() throws InterruptedException {
        SynchronousQueue<Integer> queue = new SynchronousQueue<>();
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(()-> {
            try {
                System.out.println("put元素被阻塞住...等待有人把元素拿出去");
//             * Adds the specified element to this queue, waiting if necessary for
//     * another thread to receive it.
                //这里会阻塞直到有人拿走元素
                queue.put(1);
                System.out.println("元素1被拿走了...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread.sleep(1000);
        System.out.println("去拿元素1了..");
        queue.take();

    }

    @Test
    public void testPut2() throws InterruptedException {
        SynchronousQueue<Integer> queue = new SynchronousQueue<>();
        queue.put(1);
        queue.put(2);
    }
}
